from GenHatch import genHatches
from GeomAlgo import rotatePolygons
import numpy as np
from Polyline import Polyline
from SpiltRegion import splitRegion


class GenDpPath:
    def __init__(self, polygons, interval, angle):
        self.polygons = polygons
        self.interval = interval
        self.angle = angle
        self.splitPolys = []

    def genScanYs(self, polygons):
        yMin, yMax = float("inf"), float("-inf")
        for poly in polygons:
            for pt in poly.points:
                yMin, yMax = min(pt.y, yMin), max(pt.y, yMax)
        ys = [round(y, 7) for y in np.arange(yMin + self.interval, yMax, self.interval)]
        # print(ys)
        return ys

    def linkLocalHatches(self, segs):
        poly = Polyline()
        for i, seg in enumerate(segs):
            poly.addPoint(seg.A if (i % 2 == 0) else seg.B)
            poly.addPoint(seg.B if (i % 2 == 0) else seg.A)
        return poly

    def generate(self):
        rotPolys = rotatePolygons(self.polygons, -self.angle)
        ys = self.genScanYs(rotPolys)
        self.splitPolys = splitRegion(rotPolys)
        paths = []
        for poly in self.splitPolys:
            segs = genHatches([poly], ys)
            if len(segs) > 0:
                path = self.linkLocalHatches(segs)
                paths.append(path)
        return rotatePolygons(paths, self.angle)


def genDpPath(polygons, interval, angle):
    return GenDpPath(polygons, interval, angle).generate()
